<template>
  <div class="pageLevel split-details">
    <!--        操作框-->
    <div class="tableSearch">
      <el-form label-width="15px" class="demo-ruleForm">
        <el-form-item label="">
          <el-button type="primary" size="mini" @click="back">返回</el-button>
          <el-button v-if='handle != "see"' type="primary" size='mini' @click="saveFormData('formData')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-form label-width='120px' label-position='left' :model="formData" :rules="rulesFormData" ref="formData">
      <el-form-item label="服务商类型：" prop='serviceProviderTypeNumber'>
        <el-select v-model="formData.serviceProviderTypeNumber" placeholder="服务商类型" style='width:200px'
                   @change='selectChange' size='small' :disabled='handle=="see" '>
          <el-option label='请选择' value=''></el-option>
          <el-option v-for='item in serviceProviderType' :label="item.serviceProviderTypeName" :value="item.serviceProviderTypeNumber" :key='item.serviceProviderTypeNumber'></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务商等级：" prop='serviceProviderGradeNumber'>
        <el-select v-model="formData.serviceProviderGradeNumber" placeholder="服务商等级" style='width:200px'
                   size='small' :disabled='handle=="see" '>
          <el-option label='请选择' value=''></el-option>
          <el-option v-for='item in serviceProviderGrade' :label="item.serviceProviderGradeName" :value="item.serviceProviderGradeNumber" :key='item.serviceProviderGradeNumber'></el-option>
        </el-select>
      </el-form-item>
      <h3>分润占比<span>商品毛利的分润占比</span></h3>
      <template v-if='formData.list.length > 0'>
        <el-form-item v-for='(item, index) in formData.list' 
                      :prop="'list.' + index +'.benefitScale'" :rules='ruleBenefitScale.benefitScale'
                      :label="item.gradeName+'：'" :key='item.benefitGradeId' >
          <el-input maxlength="6" class="add-input" v-model="item.benefitScale" :disabled='handle=="see"||item.isBenefit==1'
                    clearable size='small' placeholder='0-100 (保留小数点后两位)'
                    @keyup.native='replace(formData.list[index],"benefitScale")'></el-input>
          <span>%</span>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>
<script>
  import util from '@/util'
  import { mapState } from "vuex";
  import {
    findServiceProviderTypeList,
    findServiceProviderGradeByTypeList,
    findBenefitGradeList,
    addOrUpdateBenefitConfig,
    findBenefitConfigDetailsInfo,
    deleteBenefitConfig,
    findBenefitConfigList
  } from '@/api'
    export default {
        name: "splitConfig-details",
      data () {
        const validBenefitScale = (rule, value, callback)=> {
          value=value.toString()
          if(!util.validFloatNumber(value)) {
            return callback(new Error('此处只能输入数字或者小数点'));
          } else if(String(value).indexOf('.')>0){
            let arr = value.split('.')
            if(arr[0].length>2 && parseInt(arr[1]) > 0){
              return callback(new Error('只能输入0-100之间的数字'));
            }  else {
              callback();
            }
          }else {
            callback();
          }
        }
          return {
            targetId: '',
            handle: '',
            serviceProviderType: [], //服务商类型列表
            serviceProviderGrade: [], //服务商等级列表
            benefitGradeList: [{
              id: "",
              gradeName: '',
            }], //分润等级列表
            formData:{
              benefitConfigId: '',
              serviceProviderTypeNumber: '',
              serviceProviderGradeNumber: '',
              list: []
            },
            rulesFormData: {
              serviceProviderTypeNumber: [
                {required: true, message: '请选择服务商类型', trigger: 'change'},
              ],
              serviceProviderGradeNumber: [
                {required: true, message: '请选择服务商等级', trigger: 'change'},
              ]},
            ruleBenefitScale: {
              benefitScale: [{required: true, message: '请输入分润占比', trigger: 'blur'},
                {validator: validBenefitScale, trigger: 'blur'}]
            },
            pageSize: 10000,
            pageNum: 1,

          }
      },
      computed: mapState([
        "merchantId",
        "sub",
        'power',
        "isReLoadData"]),
      created() {
        this.handle = util.getQuery('handle');
        this.targetId = util.getQuery('targetId')
        if (this.handle == 'new') {
          this.getBenefitGradeList();
        } else {
          this.getdetails(this.targetId);
        }
        this.getServiceTypeList();
      },
      methods: {
        replace(obj,key) {
          console.log(obj)
          let that = this
          let event = event || window.event
          if(event.keyCode == 13){
            setTimeout(()=>{
              that.validItem(obj,key);
            },100);
          } else {
            that.validItem(obj,key);
          }
        },
        validItem(obj,key){
          let res = util.replaceTotal(obj[key],3);
          this.$set(obj,key,res);
        },
        //服务商类型
        getServiceTypeList () {
          findServiceProviderTypeList().then(res =>{
            if(res.code == 200) {
              this.serviceProviderType = res.data.list
            }
          })
        },
        //服务商类型选择
        selectChange (val) {
          if(val){
            this.getServiceGradeList(val)
            this.formData.serviceProviderGradeNumber = ''
          } else {
            this.formData.serviceProviderGradeNumber = ''
            this.serviceProviderGrade = []
          }
        },
        //服务商等级
        getServiceGradeList (num) {
          let data = {
            serviceProviderTypeNumber: num
          }
          findServiceProviderGradeByTypeList(data).then(res =>{
            if (res.code == 200) {
              this.serviceProviderGrade = res.data.list
            }
          })
        },
        //获取所有分润等级
        getBenefitGradeList(list) {
          let data = {
            shopId: this.merchantId,
            pageNum: this.pageNum,
            pageSize: this.pageSize
          }
          findBenefitGradeList(data).then(res=>{
            let data = res.data.list
            if(res.code == 200) {
              if (res.data.list.length!=0) {
                for (var i = 0 ;i<data.length;i++) {
                  let item = {
                    benefitGradeId: data[i].id,
                    gradeName: data[i].gradeName,
                    benefitScale: '',
                    isBenefit: data[i].isBenefit
                  }
                  this.formData.list.push(JSON.parse(JSON.stringify(item)))
              }
               }
              if(this.handle == 'edit'){
                console.log(list)
                if (list.list.length!=0) {
                   let dataList = this.deepCopy(list.list, this.formData.list)
                    this.formData.list = JSON.parse(JSON.stringify(dataList))
                }else{
                  this.formData.list=[]
                }
                this.formData.benefitConfigId = list.benefitConfigId
                this.formData.serviceProviderTypeNumber = list.serviceProviderTypeNumber
                this.formData.serviceProviderGradeNumber = list.serviceProviderGradeNumber
              }
            }
          })
        },
        saveFormData(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let data = JSON.parse(JSON.stringify(this.formData))
              data.shopId = this.merchantId
              addOrUpdateBenefitConfig(data).then(res =>{
                if(res.code == 200){
                  this.tips('保存成功', 'success');
                  this.back();
                }
              })
            }
          })
        },
        getdetails(id) {
         let data = {
           benefitConfigId: id
         }
          findBenefitConfigDetailsInfo(data).then(res =>{
            if(res.code == 200) {
              this.getServiceGradeList(res.data.serviceProviderTypeNumber);
              this.$nextTick(function () {
                if(this.handle == 'edit'){
                  let list  = res.data
                  this.getBenefitGradeList(list); //获取所有分润等级
                }else {
                  this.formData = res.data
                }
              })
            }
          })
        },
        //递归合并json数组取交集
        deepCopy(arr1, arr2) {
          if(arr2.length < 1) {
            arr2 = JSON.parse(JSON.stringify(arr1))
            return;
          }
          for (let i = 0; i<arr1.length;i++) {
            for (let j = 0;j<arr2.length;j++) {
              for(let key1 in arr1[i]) {
                for (let key2 in arr2[j]) {
                  if(key1 == 'benefitGradeId' && arr1[i][key1] == arr2[j][key2]) {
                    Object.assign(arr2[j], arr1[i])
                  }
                }
              }
            }
          }
          return arr2
        },
        back () {
          window.history.back(-1);
          return false;
        },
        tips(tip,type) {
          this.$message({
            message: tip,
            type: type
          });
        },
      }
    }
</script>

<style scoped lang='less'>
  .split-details{
    h3{
      padding-bottom: 20px;
      span{
        color: #A5A8AD;
        font-size: 16px;
        font-weight: normal;
        padding-left: 20px;
      }
    }
    .add-input{
       width: 200px;
    }
  }

</style>
